package com.jqb.ajax.servlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

/**
 * Created by IntelliJ IDEA.
 * User: jqbxd
 * Date: 2009-4-1
 * Time: 10:46:53
 * http数据
 */
public class AjaxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        httpServletResponse.setContentType("text/html; charset=utf-8");

        PrintWriter out = httpServletResponse.getWriter();
        //缓存问题，firefox中反复访问count会不断累加，但是在ie中相同用户访问不会累加
        //原因是url地址相同的时候ie会读取缓存
        Integer count = (Integer) httpServletRequest.getSession().getAttribute("total");
        if (count == null) {
            count = 1;
        } else {
            count = count + 1;
        }
        httpServletRequest.getSession().setAttribute("total", count);
        //1、取参数
        String old = httpServletRequest.getParameter("name");
        //乱码问题1 ，好像不加这句就可以 ，加了反而不行
//        String name = new String(old.getBytes("iso8859-1"), "utf-8");
        //乱码问题1 ，好像不加这句就可以 ，加了反而不行
        String name=URLDecoder.decode(old,"utf-8");
        //2、检查参数是否有问题
        if (name == null || name.equals("")) {
            out.println("用户名不能为空!  请重新输入!" + count);
        } else {
            //3、校验操作
            if (name.equals("jqb")) {
                //4。和传统应用不同之处。这一步需要将用户感兴趣的数据返回给页面端，而不是将一个新的页面发送给用户
                //写法没变本质发生改变
                out.println("欢迎[" + name + "]登录!" + count);
            } else {
                out.println("用户[" + name + "]不存在!" + count);
            }
        }
        //out.println("<br/><a href=\"index.html\">返回</a>");
    }

    @Override
    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        doGet(httpServletRequest, httpServletResponse);
    }
}
